from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import jwt_decode_handler
import jwt
from api import models


class JWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        jwt_value = request.META.get('HTTP_AUTHORIZATION')
        # print("jwt_value", jwt_value)
        if not jwt_value:
            # 没有值，直接抛异常
            raise AuthenticationFailed('您没有携带认证信息')
        if jwt_value:
            try:
                # jwt提供了通过三段token，取出payload的方法，并且有校验功能
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                raise AuthenticationFailed('签名过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('用户非法')
            except Exception as e:
                # 所有异常都会走到这
                raise AuthenticationFailed(str(e))
            # 因为payload就是用户信息的字典
            # 传进去一个对象，自动构建成下列的字典信息
            # payload {'user_id': 1, 'username': 's1', 'exp': 1652945457, 'orig_iat': 1650180657}
            # print("payload", payload)
            user = models.UserInfo.objects.get(pk=payload.get('user_id'))
            # print('user', user)
            return user, jwt_value
